package com.wuc.client;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;

import com.wuc.client.https.HttpUtils;
import com.wuc.client.urlkeys.WucUrlKeyInter;
import com.wuc.client.utils.WtcJsonMap;

/**
 * 参数相关
 * 
 * @author macpl
 *
 */
public class WucClient {
	private String secret;
	private String operatorLoginname;
	private String operatorPassword;
	private String baseUrl;

	public WucClient(String baseUrl, String secret, String operatorLoginname, String operatorPassword) {
		super();
		this.secret = secret;
		this.baseUrl = baseUrl;
		this.operatorLoginname = operatorLoginname;
		this.operatorPassword = operatorPassword;
	}

	/**
	 * 服务是否可用
	 * 
	 * @return
	 */
	public boolean isLive() {
		Map<String, String> data = new HashMap<String, String>();
		data.put("secret", secret);
		data.put("operatorLoginname", operatorLoginname);
		data.put("operatorPassword", operatorPassword);
		// -----------
		data.put("loginname", operatorLoginname);
		JSONObject backData = HttpUtils.httpPost(baseUrl + "/api/get/user.do", data);
		if (!backData.has("STATE") || backData.getInt("STATE") != 0) {
			throw new RuntimeException(backData.toString());
		}
		return true;
	}

	/**
	 * 查询系统参数
	 * 
	 * @param paras
	 * 
	 * @param keyPart 部分key，模糊匹配
	 */
	public String getParameter(String key, String paras) {
		Map<String, String> data = new HashMap<String, String>();
		data.put("secret", secret);
		data.put("operatorLoginname", operatorLoginname);
		data.put("operatorPassword", operatorPassword);
		// -----------
		data.put("key", key);
		if (StringUtils.isNotBlank(paras)) {
			data.put("paras", paras);
		}
		JSONObject backData = HttpUtils.httpPost(baseUrl + "/api/get/parameter.do", data);
		if (!backData.has("STATE") || backData.getInt("STATE") != 0) {
			throw new RuntimeException(backData.toString());
		}
		WtcJsonMap json = new WtcJsonMap(backData.toMap());
		return json.getString("DATA");
	}

	/**
	 * 获得系统预设服务地址
	 * 
	 * @param urlkey
	 * @return
	 */
	public String getUrl(WucUrlKeyInter urlkey) {
		if (urlkey.getParas() != null) {
			String paradots = "";
			for (String para : urlkey.getParas()) {
				paradots = paradots + "," + para;
			}
			return getParameter(urlkey.getKey(), paradots);
		} else {
			return getParameter(urlkey.getKey(), null);
		}
	}
}
